<template>
  <div>
    <!-- 企业类型薪酬变化 -->
    <el-row class="search-container">
      <el-form ref="form" label-width="auto">
        <el-form-item label="统计时间：">
          <el-date-picker
            v-model="selectBetweenTime"
            :clearable="false"
            size="small"
            type="monthrange"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            :picker-options="pickerOptions"
            @change="handleDateChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="企业规模：">
          <companyCheckbox
            :limitNum="1"
            ref="regionRef"
            @onCompanyChange="onCompanyChange"
          />
        </el-form-item>
      </el-form>
    </el-row>
    <div class="chartMain">
      <template v-if="chartDataIsNotEmpty">
        <div class="h100" ref="line_echartDom"></div>
      </template>
      <el-empty class="empty" description="暂无数据" v-else
        ><el-button type="primary" size="mini" @click="handleKnowClick()">
          想要了解
        </el-button></el-empty
      >
    </div>
  </div>
</template>

<script>
import { positionSalaryTrends, reportLackDataPosition } from '@/api/salary';
import companyCheckbox from './companyCheckbox';

export default {
  name: 'companySalaryChangesChart',
  components: {
    companyCheckbox
  },
  data() {
    return {
      resData: [],
      chartData: {},
      chartDataIsNotEmpty: true, //必须让图表先显示，不然会出现空白
      selectBetweenTime: [],
      pickerMinDate: '',
      firstDayofLastMonth: '',
      pickerOptions: {
        disabledDate: (time) => {
          const nowTime = time.getTime();
          if (nowTime < 1672502400000 || nowTime > this.firstDayofLastMonth) {
            return true;
          }
          if (this.pickerMinDate) {
            const monthsDiff =
              Math.abs(nowTime - this.pickerMinDate) /
              (1000 * 60 * 60 * 24 * 30);
            // 如果相差的月份大于6个月，则禁用该日期
            return monthsDiff > 6 || nowTime < 1672502400000;
          }
        },
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        }
      },
      average: '',
      selectedRegionList: [],
      regionLineDescAvg: '',
      isSetDeaultTime: false,
      currentChartRegionName: '',
      chartDescData: []
    };
  },
  created() {
    // 创建一个表示当前日期的 Date 对象
    var currentDate = new Date();

    // 将当前日期设置为本月的第一天
    currentDate.setDate(1);

    // 将当前日期减去一天，得到上个月最后一天
    currentDate.setDate(0);

    // 设置时间为零点
    currentDate.setHours(0, 0, 0, 0);

    // 获取时间戳
    var timestamp = currentDate.getTime();

    this.firstDayofLastMonth = timestamp;

    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let newYear = 0;
    let newMonth = 0;
    let newDateArr = [];
    for (let i = 0; i < 7; i++) {
      //这里是获取前六个月,所以循环6次,根据需要修改
      if (month - i < 1) {
        //这里的判断是如果当前月份往前推到了去年  需要做的处理
        newYear = year - 1;
        newMonth =
          month - i + 12 >= 10 ? month - i + 12 : '0' + (month - i + 12);
        newDateArr.push(newYear + '-' + newMonth + '-' + '01'); //这里拼接格式化,在时间中间加了个-,根据实际需求来
      } else {
        newMonth = month - i >= 10 ? month - i : '0' + (month - i); //这里是对月份小于10做加前面加0处理
        newDateArr.push(year + '-' + newMonth + '-' + '01');
      }
    }
    //这里就最后得到当前年月前六个月组成的时间数组,根据需要赋值使用即可
    const end = newDateArr[1];
    const start = newDateArr[6];
    this.selectBetweenTime = [start, end];
  },
  mounted() {
    // this.fetchData();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      const params = {
        ylPositionId: this.$route.query.id,
        keyType: 2,
        keyId: this.selectedRegionList[0]
      };
      if (this.selectBetweenTime != null && this.selectBetweenTime != '') {
        params.startTime = this.selectBetweenTime[0];
        params.endTime = this.selectBetweenTime[1];
      }
      //新接口08-16
      positionSalaryTrends(params)
        .then((response) => {
          if (response.code == 200) {
            this.resData = response.data;
            this.chartData = this.handleData(response.data);
            this.chartDataIsNotEmpty =
              response.data && response.data.length > 0;
            setTimeout(() => {
              this.init();
            }, 500);
            this.$emit('onChartDataChange', this.resData);
          } else {
            this.chartDataIsNotEmpty = false;
          }
        })
        .catch(() => {
          this.chartDataIsNotEmpty = false;
        });
    },
    handleData(data) {
      // 因为后端数据结构改了 这里不可能再兼容多条折线了，如果你要多条折现那就去看reruitHeatLineChart吧
      // 2024年8月16日09:57
      let dataArr = {
        industry: [],
        time: []
      };
      if (data && data.length) {
        const obj = {
          name: data[0].keyName,
          salary: []
        };

        data.forEach((dataItem) => {
          obj.salary.push(dataItem.salary);
          dataArr.time.push(this.formatDate(dataItem.calMonth));
        }),
          dataArr.industry.push(obj);
      } else {
        // this.$message.warning("该行业暂无" + this.salaryItem.title || "数据");
      }
      return dataArr;
    },
    formatDate(dateString) {
      // 解析日期字符串
      const date = new Date(dateString);

      // 获取月份和年份
      const month = date.getMonth() + 1; // getMonth() 返回 0-11，所以需要加 1
      const year = date.getFullYear();

      // 格式化为“6月2024”格式
      return `${month}月${year}`;
    },
    init() {
      if (!this.$refs['line_echartDom']) return;
      this.myChart = this.$echarts.init(this.$refs['line_echartDom']);
      let industry = this.chartData.industry;
      let time = this.chartData.time;

      let option = {
        color: [
          '#F359AE',
          '#34CA6F',
          '#066BFF',
          '#75E0FF',
          '#FFA506',
          '#3ba272',
          '#fc8452',
          '#9a60b4',
          '#ea7ccc'
        ],
        xAxis: {
          type: 'category',
          data: time,
          name: '(月份)',
          // boundaryGap: false,
          axisLabel: {
            formatter(val) {
              // 当字符串长度超过2时
              if (val.length > 2) {
                // 把字符串分割成字符串数组
                const array = val.split('');
                const index = array.indexOf('月');
                //在下标2处删除0个，加上回车
                array.splice(index + 1, 0, '\n\n');
                return array.join('');
              } else {
                return val;
              }
            },
            color: '#8193B2',
            fontSize: '12px'
          },
          axisLine: {
            lineStyle: {
              color: '#E4EDF8'
            }
          },
          nameTextStyle: {
            lineHeight: 80, //标题行高
            color: '#8193B2',
            verticalAlign: 'top', //标题位置
            fontSize: '12px', // 设置最大宽度
            padding: [-28, 0, 0, 0] // 上右下左与原位置距离
          }
        },
        tooltip: {
          trigger: 'axis'
          // formatter(val) {
          //   //console.log("val", val[0]);

          //   return val[0].seriesName;
          // },
        },
        grid: {
          right: '50',
          bottom: '50',
          top: '50',
          left: '50'
        },
        yAxis: {
          type: 'value',
          min: 0,
          splitNumber: 5,
          // minInterval: 1,
          scale: true,
          name: '（薪酬 元）',
          axisLabel: {
            color: '#8193B2',
            fontSize: '12px'
          },
          nameTextStyle: {
            padding: [0, 40, 10, 0], // 上右下左与原位置距离
            color: '#8193B2'
          }
        },
        series: []
      };
      option.series = [];
      this.myChart.clear();
      industry.forEach((item, index) => {
        option.series.push({
          data: item.salary,
          name: item.name,
          type: 'line',
          smooth: true,
          symbolSize: 10,
          symbol: 'path://M349 889.5a7.5 7.5 0 1 0 15 0a7.5 7.5 0 1 0 -15 0z',
          showSymbol: false,
          label: {
            normal: {
              show: false
            }
          },
          emphasis: {
            label: {
              // show: true,
            }
          }
        });
      });

      option && this.myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: 1
      });
    },
    onCompanyChange(val) {
      if (val && val.length) {
        this.currentChartRegionName = val[0].split('-')[1];
        this.selectedRegionList = [];
        val.forEach((item) => {
          this.selectedRegionList.push(item.split('-')[0]);
        });
      } else {
        this.currentChartRegionName = '';
        this.selectedRegionList = [];
      }
      this.fetchData();
    },
    onWorkYearChange(val) {
      this.fetchData();
    },
    handleDateChange(val) {
      if (this.isSetDeaultTime) {
        this.isSetDeaultTime = false;
        return;
      }
      this.pickerMinDate = null;
      this.fetchData();
    },
    handleKnowClick() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo')); //OA的userInfo和SaaS登录的userInfo不一样
      const oaId = '';
      if (userInfo && userInfo.user_source_id) {
        oaId = userInfo.user_source_id;
      }
      const params = {
        positionId: this.$route.query.id,
        positionName: this.$route.query.name,
        layerId: '177',
        layerName: '企业类型薪酬变化',
        personId: localStorage.getItem('personId') || '',
        oaId: oaId
      };
      reportLackDataPosition(params).then((response) => {
        if (response.code == 200) {
          this.$message.success('已成功提交');
        } else {
          this.$message.error(res.status_desc);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  margin-top: 16px;
  color: #222;
  font-weight: bold;
  margin-bottom: 22px;
  .titleFlag {
    width: 5px;
    height: 15px;
    border-radius: 3px;
    background: #4880ff;
    margin-right: 12px;
  }
}
.chartMain {
  display: flex;
  // align-items: center;
  margin-left: 0px;
  .empty {
    margin: auto;
    ::v-deep .el-empty__image {
      width: 150px;
    }
  }
  .h100 {
    flex: 0.65;
  }
  .regionLineDesc {
    /* // margin-left: 45px; */
    display: flex;
    flex: 0.35;
    flex-wrap: wrap;
    /* width: 400px; */
    justify-content: space-between;
    // align-content: center;
    margin: 10px 10px 10px 10px;
    .cityTitle {
      display: flex;
      width: 100%;
      margin: 10px auto;
      font-size: 18px;
      font-weight: bold;
      color: #222;
      align-items: center;
    }

    .regionLineDescItem {
      margin: 10px 0px;
      width: 48%;
    }
    .descTitle {
      color: #555;
      font-size: 15px;
    }
    .descNum {
      display: flex;
      align-items: baseline;
      color: #1b78ff;
      font-size: 24px;
      font-weight: bold;
      margin-top: 22px;
      font-family: D-DIN-PRO-500-Medium;
    }
    .rmb {
      font-size: 18px;
    }
  }
}
.regionLineChart {
  display: flex;
  align-items: center;
}
.regionLineDesc {
  // margin-left: 45px;
  display: flex;
  flex: 0.3;
  flex-wrap: wrap;
  // width: 400px;
  justify-content: left;
  .regionLineDescItem {
    margin: 10px;
  }
}
.descTitle {
  color: #555;
  font-size: 15px;
}
.descNum {
  display: flex;
  align-items: baseline;
  color: #1b78ff;
  font-size: 24px;
  font-weight: bold;
  margin-top: 22px;
  font-family: D-DIN-PRO-500-Medium;
}
.rmb {
  font-size: 22px;
}
.h100 {
  width: 100%;
  // height: 16vw;
  min-width: 615px;
  min-height: 280px;
}

::v-deep .el-date-editor {
  background: #fafcfe;
  border-radius: 4px;
  border: 1px solid #e4edf8;
}
::v-deep .el-form-item:last-of-type {
  margin-bottom: 0px;
}
::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
  line-height: 22px;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 内容超出容器部分隐藏 */
  text-overflow: ellipsis; /* 使用省略号表示被截断的内容 */
}
::v-deep .el-form-item {
  margin-bottom: 6px;
}
::v-deep .el-form-item__label-wrap {
  margin-left: 0px !important;
}
.search-container {
  display: flex;
  align-items: center;
  margin-left: 0px;
}
</style>
